<template>
        <div class="app-container">
            <el-card>
                <el-form label-width="80px" :label-position="labelPosition">
                    <!-- form表单 -->
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="标签名称" prop="tags">
                                <el-input  placeholder="请输入" v-model="page.tags" ></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 城市 -->
                        <el-col :span="6">
                            <el-form-item disabled label="城市" prop="province" >
                                <el-select @change="getCity" placeholder="请选择" style="width:100%;" v-model="page.province">
                                    <el-option :key="item" :label="item" :value="item" v-for="item in selectList.provinceList" ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <!-- 地区 -->
                        <el-col :span="6">
                            <el-form-item label="地区" prop="city">
                                <el-select placeholder="请选择" style="width:100%;" v-model="page.city" >
                                    <el-option :key="item" :label="item" :value="item" v-for="item in selectList.cityList" ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="企业简称" prop="shortName" >
                                <el-input v-model="page.shortName"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="状态" prop="state" >
                                <el-select placeholder="请选择" v-model="page.state" style="width:100%;">
                                    <el-option :key="item.value" :label="item.label" :value="item.value" v-for="item in status"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-button @click="resetForm" type="reset" style="font-size: 12px;margin-left:45px;">清除</el-button>
                            <el-button @click="searchData" type="primary" style="font-size: 12px;">搜索</el-button>
                        </el-col>
                        <el-col :span="12" style="text-align:right;">
                                <el-button style="font-size: 12px;" @click="showDialog=true" icon="el-icon-edit"  type="success">新增用户</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <el-alert close-text=" " show-icon :title="alertMsg" type="info" style="margin-bottom:10px;"></el-alert>
                <!-- table表格 -->
                    <el-table :data="tableData" style="width: 100%;" type="flex">
                    <el-table-column label="序号" prop="id" type="index" align="center"></el-table-column>
                    <el-table-column label="企业编号" prop="number" align="center"></el-table-column>
                    <el-table-column label="企业简称" prop="shortName" align="center"></el-table-column>
                    <el-table-column label="标签" prop="tags" align="center"></el-table-column>
                    <el-table-column label="创建者" prop="creatorID" align="center"></el-table-column>
                    <el-table-column label="创建日期" prop="addDate" :formatter="row => date(row.addDate)" align="center"></el-table-column>
                    <el-table-column label="备注" prop="remarks" align="center"></el-table-column>
                    <!-- 0是禁用状态,  1是启用状态 -->
                    <el-table-column label="状态" prop="state" align="center">
                        <template #default="{row}">
                            <span v-if="row.state==1">启用</span>
                            <span v-else>禁用</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template #default="{row}">
                            <!-- 三个按钮 -->
                            <el-row>
                                <!-- 编辑按钮 -->
                                <el-button @click="btnEdit(row)" circle icon="el-icon-edit" plain type="primary"></el-button>
                                <!-- 状态按钮 -->
                                <el-button v-if="row.state==1" @click="stateChange(row)" circle icon="el-icon-check" plain type="success"></el-button>
                                <el-button v-else @click="stateChange(row)" circle icon="el-icon-close" plain type="warning"></el-button>
                                <!-- 删除按钮 -->
                                <el-button @click="btnDel(row)" circle icon="el-icon-delete" plain type="danger"></el-button>
                            </el-row>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页组件 -->
                <el-pagination :page-size="10" :page-sizes="[2, 5, 10, 20, 30, 40]" :total="page.total" @current-change="handleCurrentChange" @size-change="handleSizeChange" background layout="prev, pager, next, sizes, jumper" style="text-align:right;margin-top:10px;"></el-pagination>
            </el-card>
            <!-- 弹窗 -->
            <el-dialog :title="formData.id ? '编辑用户' : '创建用户'" :visible="showDialog" @close="btnCancel">
                <div style="display: flex; justify-content: center;">
                    <el-form :model="formData" :rules="rules" label-width="100px" ref="formData" style="width:550px;">
                    <el-form-item label="企业名称" prop="shortName">
                        <el-input v-model="formData.shortName"></el-input>
                    </el-form-item>
                    <el-form-item label="所属公司" prop="company">
                        <el-input v-model="formData.company"></el-input>
                        <p>https://www.tianyancha.com （在此可查询所属公司全称及简称）</p>
                    </el-form-item>
                    <el-form-item label="城市">
                        <el-select @change="getCity" placeholder="请选择" style="width:150px;margin-right:10px;" v-model="formData.province">
                            <el-option :key="item" :label="item" :value="item" v-for="item in selectList.provinceList"></el-option>
                        </el-select>
                        <el-select placeholder="请选择" style="width:150px;" v-model="formData.city">
                            <el-option :key="item" :label="item" :value="item" v-for="item in selectList.cityList"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="企业标签" prop="tags">
                        <el-input v-model="formData.tags"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remarks">
                        <el-input placeholder="请输入" type="textarea" v-model="formData.remarks"></el-input>
                    </el-form-item>
                </el-form>
                </div>
                    <el-row justify="center" slot="footer" type="flex">
                    <el-col :span="6">
                        <el-button @click="btnCancel" size="small">取消</el-button>
                        <el-button @click="btnOK" size="small" type="primary">确定</el-button>
                    </el-col>
                </el-row>
            </el-dialog>
        </div>
</template>

<script>
import { list, update, add, remove, detail, disabled } from '@/api/hmmm/companys'
import { status } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'

export default {
  data () {
    return {
      labelPosition: 'right',
      alertMsg: '', // 消息总条数显示
      // 表单数据
      formData: {
        tags: '', // 企业标签
        province: '', // 城市
        city: '', // 地区
        shortName: '', // 企业名称
        company: '', // 所属公司
        remarks: '', // 备注
        isFamous: '',
        state: '',
        id: ''
      },
      // 级联选择器
      selectList: {
        provinceList: [], // 城市
        cityList: [] // 地区
      },
      page: {
        // 放置页码及相关数据
        page: 1,
        pagesize: 10, // 页面显示的数据条数
        total: null// 记录总数
        // tags: '', // 标签名称
        // province: '',
        // city: '',
        // shortName: '',
        // state: ''
      },
      showDialog: false,
      tableData: [], // 承接表格数据
      // 表单校验规则
      rules: {
        shortName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
        company: [{ required: true, message: '所属公司不能为空', trigger: 'blur' }],
        tags: [{ required: true, message: '请输入企业标签', trigger: 'blur' }],
        remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.list()
    this.getProvince()
  },
  computed: {
    status () {
      return status
    }
  },
  methods: {
    // 格式化时间
    date (isoDateStr) {
      const dateObj = new Date(isoDateStr)
      const year = dateObj.getFullYear()
      const month = String(dateObj.getMonth() + 1).padStart(2, '0')
      const day = String(dateObj.getDate()).padStart(2, '0')
      const hours = String(dateObj.getHours()).padStart(2, '0')
      const minutes = String(dateObj.getMinutes()).padStart(2, '0')
      const seconds = String(dateObj.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    /** **************************************  清除表单数据   *****************************************/
    resetForm () {
      this.formData = {}
      this.page.province = null
      this.page.city = null
      this.page.state = null
      this.page.tags = null
    },

    /** **************************************  搜索   *****************************************/
    searchData () {
    //   if (!this.tableData || this.tableData.length === 0) {
    //     this.tableData = this.dataSource // dataSource 为完整数据源
    //   }
    //   this.tableData = this.tableData.filter((item) => {
    //     return (!this.formData.tags || item.tags === this.formData.tags) &&
    //     (!this.formData.shortName || item.shortName === this.formData.shortName) &&
    //     (!this.page.province || item.province === this.page.province) &&
    //     (!this.page.city || item.city === this.page.city) &&
    //     (!this.page.state || item.state === this.page.state)
    //   })
    //   this.alertMsg = `查询到${this.tableData.length} 条结果`
      this.list()
    },

    /** **************************************  启用/禁用   *****************************************/
    async stateChange (row) {
      let status = ''
      if (row.state === 1) {
        row.state = 0
        status = '禁用'
        this.$set(row, 'icon', 'el-icon-close')
      } else {
        row.state = 1
        status = '启用'
        this.$set(row, 'icon', 'el-icon-check')
      }
      const data = { id: row.id, state: row.state }
      try {
        await this.$confirm(`已成功${row.state === 1 ? '启用' : '禁用'}, 是否继续?`, '提示', { type: 'warning' })
        const res = await disabled(data)
        console.log(res)
        if (res && res.state === 0) {
          this.$message.success(`已成功${row.state === 1 ? '启用' : '禁用'}!`)
          this.list()
        } else {
          this.$message.success(`已成功${row.state === 1 ? '启用' : '禁用'}!`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(`${status}失败!`)
        } else {
          row.state = row.state === 1 ? 0 : 1
          row.icon = row.state === 1 ? 'el-icon-check' : 'el-icon-close'
          this.$message.info('已取消操作!')
        }
      }
    },

    /** **************************************  获取列表数据   *****************************************/
    async list () {
      const { data } = await list(this.page)
      //   console.log(data)
      this.tableData = data.items
      //   console.log(this.tableData)
      this.page.total = data.counts
      this.alertMsg = `共${this.page.total}条记录`
    },

    /** **************************************  弹窗   *****************************************/
    // 取消弹窗
    btnCancel () {
      // 1.关闭弹窗
      this.showDialog = false
      // 2.清空表单校验规则
      this.$refs.formData.clearValidate()
      // 3.清空表单数据
      this.formData = {}
    },
    // 确定弹窗
    async btnOK () {
      try {
        // 手动校验表单
        await this.$refs.formData.validate()
        // 判断是否有id,调取接口
        if (this.formData.id) {
          // 编辑接口
          await update({ ...this.formData, id: this.formData.id, isFamous: true })
        } else {
          // 新增接口
          await add({ ...this.formData, id: this.formData.id, isFamous: true })
        }
        this.page = {
          page: 1,
          pagesize: 10, // 页面显示的数据条数
          total: null // 记录总数
        }
        await this.list()
        // 关闭弹窗
        this.showDialog = false
        // 提示信息
        this.$message.success(this.formData.id ? '编辑成功' : '创建成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑
    async btnEdit (data) {
      // 1.显示弹窗
      this.showDialog = true
      // 2.数据回填
      this.formData = await detail(data)
      // 3.找到当前行的数据
      const row = this.tableData.find((item) => item.id === data.id)
      // 4.将当前行的数据赋值给表单
      this.formData = { ...row }
    },
    // 删除
    async btnDel (id) {
      try {
        // 1.提醒用户
        await this.$confirm('此操作将永久删除用户 , 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'waring'
        })
        // 2.调用接口
        await remove(id)
        // 3.刷新页面
        this.list()
        // 4.提示信息
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },

    /** **************************************  分页   *****************************************/
    // 分页
    handleSizeChange (val) {
      //   console.log(`每页 ${val} 条`)
      this.page.pagesize = val
      this.list()
    },
    handleCurrentChange (val) {
      //   console.log(`当前页: ${val}`)
      this.page.page = val
      this.list()
    },

    /** **************************************  级联选择器   *****************************************/
    // 获取城市
    getProvince: function () {
      this.selectList.provinceList = provinces()
    },
    // 通过城市获取到地区
    getCity: function (e) {
      this.selectList.cityList = citys(e)
      this.page.city = this.selectList.cityList[0]
    }
  }
}
</script>

<style scoped>
  .el-input__inner {
    width: 100%;
  }
@media screen and (max-width: 767px) {
  /* 应用特定的样式 */
  body {
    font-size: 14px;
  }
  #sidebar {
    display: none;
  }
}
</style>
